var app = getApp()
var util = require('../../../utils/util.js');
var netWork = require('../../../utils/netutil.js');
var config = require('../../../utils/config.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // listArray: [''],
    baseDataArray:new Array(),//筛选数据备份的数据源
    fromCity: '',
    toCity: '',
    goDate: '',
    goWeek:'',
    T_isSelectHighSpeedTrain:false,//是否是只查看高铁动车票
    trainStandard:new Array(),//差标信息
    showStandardAlert: false,//是否提示差标不符合信息
    standardReason:'',//超标原因
    /**筛选 */
    isShowFilter:false,
    isTimeUp:false,
    isRunTimeUp:false,
    trainType:0,//筛选列车类型
    midTrainType:0,
    trainTime:0,//筛选发车时间
    midTrainTime:0,
    trainInfo:null,
    cabinInfo:null,
    limit:true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.data.fromCity = JSON.parse(options.T_fromCity);
    that.data.toCity = JSON.parse(options.T_toCity);
    that.data.goDate = options.T_goDate;
    that.data.goWeek = options.T_goWeek;
    that.data.T_isSelectHighSpeedTrain = options.T_isSelectHighSpeedTrain;

    //load main data
    that.loadData(that.data.goDate);
    //get 差标信息
    that.getTravelStandard();
    wx.setNavigationBarTitle({
      title: that.data.fromCity.Name + '-' + that.data.toCity.Name
    })
    that.setData({
      goDate:that.data.goDate,
      goWeek:that.data.goWeek,
    })
  },
  //load the main data
  loadData: function (dateStr) {
    var that = this;
    that.showLoading();

    var postData = that.preparePostDic(dateStr);
    var url = config.getBaseUrl('Train', 'DownLoadTrainLine');
    netWork.post(
      url,
      postData,
      function (res) {//success
        wx.hideLoading()
        console.log(res.data);
        if (res.data.ResponseMetaInfo.StatusCode == '0') {
          var listArray = res.data.Data.DataList;

          // //勾选只查看高铁动车,剔除普通
          console.log('是否选择了查看动车');
          console.log(that.data.T_isSelectHighSpeedTrain);
          for (var i = 0;i < listArray.length;i++) {
            if (that.data.T_isSelectHighSpeedTrain) {
              if (!(listArray[i].TrainType == '高铁' || listArray[i].TrainType == '动车')) {
                listArray.splice(i, 1);
              }
            }
          }
          
          //cell上展开折叠内容筛选
          var itemArray = that.choiceTheShowItem(listArray);
          //添加cell展开折叠控制字段
          for (var i = 0; i < listArray.length; i++) {
            listArray[i].cellSelect = 'N';
            listArray[i].itemArray = itemArray[i];
            //不规范格式处理
            var time = listArray[i].RunTime - 0;
            var timeStr = Math.floor(time / 60) + '时' + (time % 60) + '分';
            listArray[i].RunTime = timeStr;

            
          }

          var title =
            wx.setNavigationBarTitle({
              title: that.data.fromCity.Name + '-' + that.data.toCity.Name + '(' + listArray.length + ')',
            })
          //刷新列表
          that.setData({
            listArray: listArray,
            baseDataArray:listArray,

          })
        }else {
          wx.showToast({
            title: res.data.ResponseMetaInfo.Reason,
          })
        }
      },
      function (res) {//fail
        wx.hideLoading()
      }
    )
  },
  //创建请求列表数据所需的postDic
  preparePostDic: function (dateStr) {
    var that = this;
    var postDic = new Object();
    postDic.FromStation = that.data.fromCity.Name;//出发城市
    postDic.ToStation = that.data.toCity.Name;////到达城市
    postDic.FromDate = dateStr; //出发日期
    console.log('yy' + that.data.goDate);
    return postDic;
  },
  //筛选出需要显示的item（根据价格是否为零，或者为空）
  choiceTheShowItem: function (dataArray) {
    var itemArray = new Array();
    for (var i = 0; i < dataArray.length; i++) {
      //重组seatData
      var cellArr = new Array();
      var arr = [
        { 'name': '无座', 'price': dataArray[i].WZ + 0, 'count': dataArray[i].WZ_Y + 0,'type':'1'},
        { 'name': '硬座', 'price': dataArray[i].YZ + 0, 'count': dataArray[i].YZ_Y + 0, 'type': '2'},
        { 'name': '软座', 'price': dataArray[i].RZ + 0, 'count': dataArray[i].RZY + 0, 'type': '3'},
        { 'name': '硬卧', 'price': dataArray[i].YW + 0, 'count': dataArray[i].YW_Y + 0, 'type': '4'},
        { 'name': '软卧', 'price': dataArray[i].RW + 0, 'count': dataArray[i].RW_Y + 0, 'type': '5'},
        { 'name': '高级软卧', 'price': dataArray[i].GJRW + 0, 'count': dataArray[i].GJRW_Y + 0, 'type': '6'},
        { 'name': '二等座', 'price': dataArray[i].EDZ + 0, 'count': dataArray[i].EDZ_Y + 0, 'type': '7'},
        { 'name': '一等座', 'price': dataArray[i].YDZ + 0, 'count': dataArray[i].YDZ_Y + 0, 'type': '8'},
        { 'name': '特等座', 'price': dataArray[i].TZ + 0, 'count': dataArray[i].TZ_Y + 0, 'type': '9'},
        { 'name': '商务座', 'price': dataArray[i].SWZ + 0, 'count': dataArray[i].SWZ_Y + 0, 'type': '10'},
      ];

      //reset the seatInfoDic
      for (var j = 0; j < arr.length; j++) {
        if (arr[j].price > 0) {
          var itemDic = new Object();
          itemDic.name = arr[j].name;
          itemDic.price = arr[j].price;
          itemDic.count = arr[j].count;
          itemDic.type = arr[j].type;

          //add the dic to seatArray
          cellArr.push(itemDic);
        }
      }
      //add the seatArray to fatherArray
      itemArray.push(cellArr);
    }
    return itemArray;
  },
  //show the request loading..
  showLoading: function () {
    wx.showLoading({
      title: '加载中...',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 6000)
  },
  //cell上折叠开关
  openOrClose: function (res) {
    var that = this;
    var index = res.currentTarget.dataset.index;
    console.log('cell:' + index);

    var status = that.data.listArray[index].cellSelect;
    if (status == 'N') {
      that.data.listArray[index].cellSelect = 'Y';
    } else {
      that.data.listArray[index].cellSelect = 'N';
    }

    that.setData({
      listArray: that.data.listArray
    })
  },
  /**
 * 查询差标信息
 */
  getTravelStandard: function () {
    var that = this;
    var postData = new Object();
    postData.UserID = app.globalData.TUserInfo.UserID
    var url = config.getBaseUrl('CommonApi', 'GetTravelStandard');
    netWork.post(
      url,
      postData,
      function (res) {//success
        console.log('差标.');
        console.log(res.data);
        if (res.data.ResponseMetaInfo.StatusCode == '0') {
          //未配置会返回null
          var travelStandard = res.data.Data.TravelStandard;
          if (travelStandard != null) {
            var trainLimit = travelStandard.TrainLimit.split('|');
            console.log('trainLimit');
            console.log(trainLimit);
            that.data.trainStandard = trainLimit;
          }else {
            that.setData({
              limit:false,
            })
          }
        }
         else {
         
        }
      },
      function (res) {//fail
      }
    )
  },
  //关闭alertView
  closeAlertView:function() {
    var that = this;
    that.setData ({
      showStandardAlert:false
    })
  },
  //继续预定
  continueOrder:function() {
    var that = this;
    if (that.data.standardReason.length == 0) {
      wx.showToast({
        title: '请填写原因',
      })
      return;
    }else {
      that.setData({
        showStandardAlert: false
      })
        // 跳转下单页
      that.jumpToOrderVc(that.data.trainInfo, that.data.cabinInfo,true);
    }
    
  },
  //选择其他
  changeOther:function() {
    var that = this;
    that.setData({
      showStandardAlert: false
    })
  },
  //差标继续预定原因
  resonInput:function(res) {
    var that = this;
    console.log(res.detail.value);
    that.data.standardReason = res.detail.value;
  },

  /**
   * 底部筛选
   */
  //筛选
  filterTap:function() {
    var that = this;
    that.data.midTrainType = that.data.trainType;
    that.data.midTrainTime = that.data.trainTime;
    that.setData({
      isShowFilter: !that.data.isShowFilter,
    })
  },
  //时间
  timeTap:function() {
    var that = this;
    that.data.isTimeUp = !that.data.isTimeUp;
    that.sortTheTimeByOffTime(that.data.isTimeUp);
  },
  //耗时
  runtimeTap:function() {
    var that = this;
    that.data.isRunTimeUp = !that.data.isRunTimeUp;
    that.sortTheTimeByRunTime(that.data.isRunTimeUp);
  },

  ///时间排序抽取方法，
  sortTheTimeByOffTime: function (isUp) {
    var that = this;
    var listArray = that.data.listArray;
    var temp = null;
    for (var i = 0; i < listArray.length - 1; i++) {
      for (var j = 0; j < listArray.length - 1 - i; j++) {
        var a = listArray[j].GoTime;
        var b = listArray[j + 1].GoTime;
        if (isUp) {
          if (a > b) {
            temp = listArray[j + 1];
            listArray[j + 1] = listArray[j];
            listArray[j] = temp;
          }
        }
        else {
          if (a < b) {
            temp = listArray[j + 1];
            listArray[j + 1] = listArray[j];
            listArray[j] = temp;
          }
        }
      }
    }

    that.setData({
      listArray: listArray,
      timeIsUp: isUp,
      sortSelect: 2,

    })
  },
  ///耗时排序收取方法
  sortTheTimeByRunTime: function (isUp) {
    var that = this;
    var listArray = that.data.listArray;
    var temp = null;
    for (var i = 0; i < listArray.length - 1; i++) {
      for (var j = 0; j < listArray.length - 1 - i; j++) {
        var aa = listArray[j].RunTime;
        var newA = aa.split('时').join(' ').split('分').join('');
        var aaa = newA.split(' ');
        var a = (aaa[0] - 0) * 60 + (aaa[1] - 0);
        var bb = listArray[j + 1].RunTime;
        var newB = bb.split('时').join(' ').split('分').join('');
        var bbb = newB.split(' ');
        var b = (bbb[0] - 0) * 60 + (bbb[1] - 0);
        if (isUp) {
          if (a > b) {
            temp = listArray[j + 1];
            listArray[j + 1] = listArray[j];
            listArray[j] = temp;
          }
        }
        else {
          if (a < b) {
            temp = listArray[j + 1];
            listArray[j + 1] = listArray[j];
            listArray[j] = temp;
          }
        }
      }
    }

    that.setData({
      listArray: listArray,
      timeIsUp: isUp,
      sortSelect: 2,

    })
  },
  //筛选取消
  filterCancel:function() {
    var that = this;
    that.setData({
      isShowFilter:false,
    })
  },
  //筛选确定
  filterSure:function() {
    var that = this;
    that.data.trainType = that.data.midTrainType;
    that.data.trainTime = that.data.midTrainTime;

    
    //load the 
    that.setData({
      isShowFilter: false,
    })
    
    //filter the data
    that.filterTheTrainByTrainTypeAndTime(that.data.trainType,that.data.trainTime);
  },
  //清空筛选条件
  clearFilter:function() {
    var that = this;
    that.setData({
      midTrainType:0,
      midTrainTime:0
    })
  },
  //筛选选择列车类型0,1,2
  chooseTrainType: function (res) {
    var that = this;
    var midTrainType = res.currentTarget.dataset.type;
    console.log(midTrainType);
    that.setData({
      midTrainType: midTrainType,
    })
  },
  //筛选选择时段0,1,2,3
  chooseTrainTime:function(res) {
    var that = this;
    var midTrainTime = res.currentTarget.dataset.timetype;
    console.log('11');
    console.log(midTrainTime);
    that.setData({
      midTrainTime: midTrainTime,
    })
  },
  //筛选车次，发车时段
  filterTheTrainByTrainTypeAndTime:function(trainType,trainTime) {
    var that = this;
    var arr = that.data.baseDataArray;
    var newArr = new Array();
    //stepOne Type
    if (trainType == '0') {//不限
      newArr = arr;
    }
    else if (trainType == '1'){//高铁动车
      for(var i = 0;i < arr.length;i++) {
        if (arr[i].TrainType == '高铁' || arr[i].TrainType == '动车') {
          newArr.push(arr[i]);
        }
      }
    }
    else if (trainType == '2') {//普通列车
      for (var i = 0; i < arr.length; i++) {
        if (arr[i].TrainType != '高铁' && arr[i].TrainType != '动车') {
          newArr.push(arr[i]);
        }
      }
    }

    //Time
    if(trainTime == '0') {//不限
      
    }
    else if (trainTime == '1') {//上午（0:00-12:00）
      for (var i = 0; i < newArr.length; i++) {
        // var goTime = newArr[i].GoTime;
        if (!(newArr[i].GoTime >= '00:00' && newArr[i].GoTime <= '12:00')) {
          newArr.splice(i,1);
        }
      }
    }
    else if (trainTime == '2') {//下午(12:00-18：00)
      for (var i = 0; i < newArr.length; i++) {
        if (!(newArr[i].GoTime >= '12:00' && newArr[i].GoTime <= '18:00')) {
          newArr.splice(i, 1);
        }
      }
    }
    else if (trainTime == '3') {//晚上(18:00-23:59)
      for (var i = 0; i < newArr.length; i++) {
        if (!(newArr[i].GoTime >= '18:00' && newArr[i].GoTime <= '23:59')) {
          newArr.splice(i, 1);
        }
      }
    }

    //刷新数据
    that.setData ({
      listArray:newArr,
    })
  },
  //选择日期
  selectDateTap:function() {
    var that = this;
    wx.navigateTo({//type：0-火车票，1-国内机票
      url: '../../dateSelect/dateSelect?startDate=' + that.data.goDate + '&isStartDate=' + 1 + '&type=' + 0
    })
  },
  //前一天
  theDayBefore:function() {
    var that = this;
    var dateStr = that.data.goDate;
    var theDayBefore = util.getTheDayBeforeDate(dateStr, true);
    //load new data
    that.loadData(theDayBefore);
    var weekStr = util.getTheDateWeek(theDayBefore);

    that.setData({
      goDate: theDayBefore,
      goWeek: weekStr,
    })
  },
  //后一天
  theDayAfter:function() {
    var that = this;
    var dateStr = that.data.goDate;
    var theDayAfter = util.getTheDayBeforeDate(dateStr, false);
    var weekStr = util.getTheDateWeek(theDayAfter);

    that.setData({
      goDate: theDayAfter,
      goWeek: weekStr,
    })
    //load new data
    that.loadData(theDayAfter);
  },
  //callBack选择日期回调函数--
  updateTrainStartDate: function (dateStr, weekStr) {
    var that = this;
    //load new data
    that.loadData(dateStr);
    that.setData({
      goDate: dateStr,
      goWeek: weekStr,
    })
  },

  orderTap: function (res) {
    var that = this;
    var cellindex = res.currentTarget.dataset.cellindex;
    var index = res.currentTarget.dataset.index;
    console.log(cellindex + '..' + index);
    var trainInfo = that.data.listArray[cellindex];
    var cabinInfo = trainInfo.itemArray[index];
    that.data.trainInfo = trainInfo;
    that.data.cabinInfo = cabinInfo;
    //差标判断
    var isShowAlert = true;
    var trainStandardArr = that.data.trainStandard;
    console.log(trainStandardArr);
    if(trainStandardArr != null && trainStandardArr.length > 0) {
      for (var i = 0; i < trainStandardArr.length; i++) {
        console.log('cabinType');
        console.log(cabinInfo.type);
        if (trainStandardArr[i] == cabinInfo.type) {
          isShowAlert = false;
        }
      }
    }else {
      isShowAlert = false;
    }
    
    that.setData({
      showStandardAlert: isShowAlert,
    })
    if (isShowAlert) {
      console.log('show');
      console.log(isShowAlert);
      return;
    }

    //跳转下单页
    that.jumpToOrderVc(trainInfo,cabinInfo,false);
  },
  //跳转下单页
  jumpToOrderVc: function (trainInfo, cabinInfo, IsOverStandard) {
    var that = this;
    wx.navigateTo({
      url: '../../train/order/order?trainInfo=' + JSON.stringify(trainInfo) + '&cabinInfo=' + JSON.stringify(cabinInfo) + '&goDate=' + that.data.goDate + '&goWeek=' + that.data.goWeek + '&fromCity=' + JSON.stringify(that.data.fromCity) + '&toCity=' + JSON.stringify(that.data.toCity) + '&standardAlertReason=' + that.data.standardReason + '&IsOverStandard=' + IsOverStandard
    })    
  }
})